package com.i_art_engineer.meigong;

import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.i_art_engineer.meigong.base.BaseApplication;
import com.i_art_engineer.meigong.photo.cache.ACache;
import com.i_art_engineer.meigong.photo.font.FontSourceProcessor;
import com.i_art_engineer.meigong.util.StringUtils;
import com.i_art_engineer.meigong.widget.LoadingAndRetryManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 */
public class AppContext extends BaseApplication {

    private static AppContext instance;

    private static AppDatabase database;

    public static final String KEY_APP_ID = "app.uid";
    public static final String KEY_APP_TICKET = "app.ticket";

    public static final String KEY_USER_ID = "user.uid";
    public static final String KEY_USER_NICKNAME = "user.nickname";
    public static final String KEY_USER_AVATAR = "user.avatar";

    public List<Typeface> getFontType() {
        return fontType;
    }

    public List<Typeface> fontType=new ArrayList<Typeface>();
    private static String appTicket;

    public ACache getmCache() {
        return mCache;
    }

    public void setmCache(ACache mCache) {
        this.mCache = mCache;
    }

    private ACache mCache;
    private String[] fontname={
            "kaiti.ttf",
            "lishu.ttf",
            "song.ttf",
            "xihei.ttf",
            "xinwei.ttf",
            "youyuan.ttf"
    };
    public int getOperateViewHeight() {
        return operateViewHeight;
    }

    public void setOperateViewHeight(int operateViewHeight) {
        this.operateViewHeight = operateViewHeight;
    }

    public int operateViewHeight=0;

    public int getOperateViewWidth() {
        return operateViewWidth;
    }

    public void setOperateViewWidth(int operateViewWidth) {
        this.operateViewWidth = operateViewWidth;
    }

    public int operateViewWidth=0;
    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;

        // 注册App异常崩溃处理器
        Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());

        LoadingAndRetryManager.BASE_RETRY_LAYOUT_ID = R.layout.view_loading_retry;
        LoadingAndRetryManager.BASE_LOADING_LAYOUT_ID = R.layout.view_loading_hint;
        LoadingAndRetryManager.BASE_EMPTY_LAYOUT_ID = R.layout.view_loading_empty;

        AsyncHttpClient client = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        client.setCookieStore(myCookieStore);
        AppHttpClient.setHttpClient(client);
        database = new AppDatabase(this.getApplicationContext());
        mCache = ACache.get(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<fontname.length;i++)
                     fontType.add(i,FontSourceProcessor.getTypeface(fontname[i], AppContext.this, fontname[i]));
            }
        }).start();
    }

    public static AppContext instance() {
        return instance;
    }

    public static AppDatabase db(){ return database; }

    /**
     * 获取App安装包信息
     *
     * @return
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }

    /**
     * 判断当前版本是否兼容目标版本的方法
     *
     * @param VersionCode
     * @return
     */
    public static boolean isMethodsCompat(int VersionCode) {
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    /**
     * 获取App唯一标识
     *
     * @return
     */
    public String getAppId() {
        String uniqueID = getProperty(KEY_APP_ID);
        if (StringUtils.isEmpty(uniqueID)) {
            uniqueID = UUID.randomUUID().toString();
            setProperty(KEY_APP_ID, uniqueID);
        }
        return uniqueID;
    }

    /**
     * 用户注销
     */
    public void Logout() {
        cleanUserInfo();
        cleanTicket();
    }

    /**
     * 清除用户信息
     */
    public static void cleanUserInfo() {
        removeProperty(KEY_USER_ID, KEY_USER_NICKNAME, KEY_USER_AVATAR);
    }

    // 用户登录令牌操作

    public static void cleanTicket() {
        appTicket = "";
        removeProperty(KEY_APP_TICKET);
        AppHttpClient.cleanTicket();
    }

    public static String getTicket(){
        if (appTicket == null || appTicket == "") {
            appTicket = getProperty(KEY_APP_TICKET);
        }
        return appTicket;
    }

    public static void setTicket(String ticket){
        appTicket = ticket;
        setProperty(KEY_APP_TICKET, appTicket);
        AppHttpClient.setTicket(appTicket);
    }

    // SharedPreferences操作

    public static void setProperty(String key, String value) {
        SharedPreferences.Editor editor = getPreferences().edit();
        editor.putString(key, value);
        apply(editor);
    }

    public static String getProperty(String key) {
        return getPreferences().getString(key, null);
    }

    public static void setSetProperty(String key, Set<String> value) {
        SharedPreferences.Editor editor = getPreferences().edit();
        editor.putStringSet(key, value);
        apply(editor);
    }

    public static Set<String> getSetProperty(String key) {
        return getPreferences().getStringSet(key, null);
    }

    public static void removeProperty(String... keys) {
        for (String key : keys) {
            SharedPreferences.Editor editor = getPreferences().edit();
            editor.putString(key, null);
            apply(editor);
        }
    }
   public int[] getWH()
   {
       int ret[]=new int[2];
       WindowManager wm = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);

       int width = wm.getDefaultDisplay().getWidth();
       int height = wm.getDefaultDisplay().getHeight();
      ret[0]=width;
       ret[1]=height;
       return ret;
   }
    public String getAvailMemory() {// 获取android当前可用内存大小

        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);

        return Formatter.formatFileSize(getBaseContext(), mi.availMem);// 将获取的内存大小规格化
    }

    public String getTotalMemory() {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;

        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }

            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();

        } catch (IOException e) {
        }
        return Formatter.formatFileSize(getBaseContext(), initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }

}
